#!/bin/bash

# 测试块分配同步功能的脚本
# 该脚本用于验证 allocateBlocks 操作后，分配的块信息能否正确同步到从节点

set -e  # 如果任何命令失败，脚本退出

echo "=== 测试块分配同步功能 ==="

# MetaServer集群地址
LEADER_HOST="localhost"
LEADER_PORT="8300"
FOLLOWER1_HOST="localhost"
FOLLOWER1_PORT="8301"
FOLLOWER2_HOST="localhost"
FOLLOWER2_PORT="8302"

# 测试文件信息
TEST_FILE="/test/sync_test_file_$(date +%s).txt"  # 使用时间戳避免冲突
FILE_SIZE=1048576  # 1MB

# 检查jq是否可用
if ! command -v jq &> /dev/null; then
    echo "警告: jq 命令不可用，输出将不会格式化"
    JQ_CMD="cat"
else
    JQ_CMD="jq ."
fi

echo "1. 创建测试文件: $TEST_FILE"
CREATE_RESPONSE=$(curl -s -X POST "http://$LEADER_HOST:$LEADER_PORT/api/v1/meta/create" \
    -H "Content-Type: application/json" \
    -H "fileSystemName: minfs" \
    -d "{\"path\":\"$TEST_FILE\",\"type\":\"FILE\"}")

echo "创建文件响应:"
echo "$CREATE_RESPONSE" | $JQ_CMD

# 检查创建是否成功
if echo "$CREATE_RESPONSE" | grep -q '"success":true'; then
    echo "✅ 文件创建成功"
else
    echo "❌ 文件创建失败"
    exit 1
fi

echo -e "\n2. 在Leader节点分配块"
ALLOCATE_RESPONSE=$(curl -s -X POST "http://$LEADER_HOST:$LEADER_PORT/api/v1/meta/allocateBlocks" \
    -H "Content-Type: application/json" \
    -H "fileSystemName: minfs" \
    -d "{\"fileId\":\"$TEST_FILE\",\"bytes\":$FILE_SIZE}")

echo "Leader节点分配结果:"
echo "$ALLOCATE_RESPONSE" | $JQ_CMD

# 检查分配是否成功
if echo "$ALLOCATE_RESPONSE" | grep -q '"success":true'; then
    echo "✅ 块分配成功"
else
    echo "❌ 块分配失败"
    exit 1
fi

echo -e "\n3. 等待同步完成..."
sleep 8  # 增加等待时间确保同步完成

echo -e "\n4. 检查Leader节点的块信息"
LEADER_BLOCKS=$(curl -s "http://$LEADER_HOST:$LEADER_PORT/api/v1/meta/getBlocks?fileId=$TEST_FILE" \
    -H "fileSystemName: minfs")
echo "Leader节点块信息:"
echo "$LEADER_BLOCKS" | $JQ_CMD

echo -e "\n5. 检查Follower1节点的块信息"
FOLLOWER1_BLOCKS=$(curl -s "http://$FOLLOWER1_HOST:$FOLLOWER1_PORT/api/v1/meta/getBlocks?fileId=$TEST_FILE" \
    -H "fileSystemName: minfs")
echo "Follower1节点块信息:"
echo "$FOLLOWER1_BLOCKS" | $JQ_CMD

echo -e "\n6. 检查Follower2节点的块信息"
FOLLOWER2_BLOCKS=$(curl -s "http://$FOLLOWER2_HOST:$FOLLOWER2_PORT/api/v1/meta/getBlocks?fileId=$TEST_FILE" \
    -H "fileSystemName: minfs")
echo "Follower2节点块信息:"
echo "$FOLLOWER2_BLOCKS" | $JQ_CMD

echo -e "\n7. 比较同步结果"
# 提取块数量进行比较
LEADER_COUNT=$(echo "$LEADER_BLOCKS" | grep -o '"totalBlocks":[0-9]*' | grep -o '[0-9]*' || echo "0")
FOLLOWER1_COUNT=$(echo "$FOLLOWER1_BLOCKS" | grep -o '"totalBlocks":[0-9]*' | grep -o '[0-9]*' || echo "0")
FOLLOWER2_COUNT=$(echo "$FOLLOWER2_BLOCKS" | grep -o '"totalBlocks":[0-9]*' | grep -o '[0-9]*' || echo "0")

echo "块数量比较:"
echo "  Leader: $LEADER_COUNT 个块"
echo "  Follower1: $FOLLOWER1_COUNT 个块"
echo "  Follower2: $FOLLOWER2_COUNT 个块"

if [ "$LEADER_COUNT" = "$FOLLOWER1_COUNT" ] && [ "$LEADER_COUNT" = "$FOLLOWER2_COUNT" ]; then
    echo "✅ 同步成功: 所有节点的块数量一致"
else
    echo "❌ 同步失败: 节点间块数量不一致"
fi

echo -e "\n8. 检查Leader节点的同步状态"
SYNC_STATUS=$(curl -s "http://$LEADER_HOST:$LEADER_PORT/admin/sync/status")
echo "同步状态:"
echo "$SYNC_STATUS" | $JQ_CMD

echo -e "\n=== 测试完成 ==="
